import { AutoComplete, Button, Icon, Image, Input, Modal, Popover } from "@arco-design/web-react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import '../components/styles.css';
import MBProtocalFactory from '../../../sdk/module/mb_constants'
import IMSDK from '../../../sdk'

import uuid from "../../../sdk/module/uuid";
import { ConversationType, MessageType } from "../../../domain/im/entity";
import { UserModelBlock } from "../../friend/components/user_model";
import { useDispatch, useSelector } from "react-redux";
import { updateVideoUserId } from "../../../store/features/user";
import { IconInfoCircle } from "@arco-design/web-react/icon";
import { UseIsGroupUser } from "../hook/is_group_user";
import { MentionsInput, Mention } from 'react-mentions'

// 没办法 arco 太难用了 满足不了
// import { Mentions } from "antd";


// import { UseIsGroupUser } from "../hook/is_group_user";


// import { WebRtcModel } from "./webrtc_model";

type EmojiMapping = Record<string, string>;






const defaultStyle = {
    control: {
      backgroundColor: '#fff',
      fontSize: 16,
      fontWeight: 'normal',
    },
  
    '&multiLine': {
      control: {
        fontFamily: 'monospace',
        minHeight: 63,
      },
      highlighter: {
        padding: 9,
        border: '1px solid transparent',
      },
      input: {
        paddingLeft: '14px',
        width: '780px'
        // border: '1px solid silver',
      },
    },
  
    '&singleLine': {
      display: 'inline-block',
      width: 180,
  
      highlighter: {
        padding: 1,
        border: '2px inset transparent',
      },
      input: {
        padding: 1,
        border: '2px inset',
      },
    },
  
    suggestions: {
      list: {
        backgroundColor: 'white',
        border: '1px solid rgba(0,0,0,0.15)',
        fontSize: 14,
    
      },
      item: {
        padding: '5px 15px',
        borderBottom: '1px solid rgba(0,0,0,0.15)',
        '&focused': {
          backgroundColor: '#cee4e5',
        },
      },
    },
  }
  
export const emojis: EmojiMapping = {
    '[微笑]': 'hehe.png',
    '[撇嘴]': 'piezui.png',
    '[色]': 'se.png',
    '[发呆]': 'fadai.png',
    '[得意]': 'deyi.png',
    '[流泪]': 'liulei.png',
    '[害羞]': 'haixiu.png',
    '[闭嘴]': 'bizui.png',
    '[睡]': 'shui.png',
    '[大哭]': 'daku.png',
    '[尴尬]': 'ganga.png',
    '[发怒]': 'fanu.png',
    '[调皮]': 'tiaopi.png',
    '[呲牙]': 'ciya.png',
    '[惊讶]': 'jingya.png',
    '[难过]': 'nanguo.png',
    '[囧]': 'jiong.png',
    '[抓狂]': 'zhuakuang.png',
    '[吐]': 'tu.png',
    '[偷笑]': 'touxiao.png',
    '[愉快]': 'yukuai.png',
    '[白眼]': 'baiyan.png',
    '[傲慢]': 'aoman.png',
    '[困]': 'kun.png',
    '[惊恐]': 'jingkong.png',
    '[流汗]': 'liuhan.png',
    '[憨笑]': 'hanxiao.png',
    '[悠闲]': 'youxian.png',
    '[奋斗]': 'fendou.png',
    '[咒骂]': 'zhouma.png',
    '[疑问]': 'yiwen.png',
    '[嘘]': 'xu.png',
    '[晕]': 'yun.png',
    '[衰]': 'sui.png',
    '[骷髅]': 'kulou.png',
    '[敲打]': 'qiaoda.png',
    '[再见]': 'zaininmadejian.png',
    '[擦汗]': 'cahan.png',
    '[抠鼻]': 'koubi.png',
    '[鼓掌]': 'guzhang.png',
    '[坏笑]': 'huaixiao.png',
    '[左哼哼]': 'zuohengheng.png',
    '[右哼哼]': 'youhengheng.png',
    '[哈欠]': 'haqian.png',
    '[鄙视]': 'bishi.png',
    '[委屈]': 'weiqu.png',
    '[快哭了]': 'kuaikule.png',
    '[阴险]': 'yinxian.png',
    '[亲亲]': 'qinqin.png',
    '[可怜]': 'kelian.png',
    '[菜刀]': 'caidao.png',
    '[西瓜]': 'xigua.png',
    '[啤酒]': 'pijiu.png',
    '[咖啡]': 'kafei.png',
    '[猪头]': 'zhutou.png',
    '[玫瑰]': 'meigui.png',
    '[凋谢]': 'diaoxie.png',
    '[嘴唇]': 'zuichun.png',
    '[爱心]': 'aixin.png',
    '[心碎]': 'xinsui.png',
    '[蛋糕]': 'dangao.png',
    '[炸弹]': 'zhadan.png',
    '[便便]': 'bianbian.png',
    '[月亮]': 'yueliang.png',
    '[太阳]': 'taiyang.png',
    '[拥抱]': 'yongbao.png',
    '[强]': 'qiang.png',
    '[弱]': 'ruo.png',
    '[握手]': 'woshou.png',
    '[胜利]': 'shengli.png',
    '[抱拳]': 'baoquan.png',
    '[勾引]': 'gouyin.png',
    '[拳头]': 'quantou.png',
    '[OK]': 'ok.png',
    '[跳跳]': 'tiaotiao.png',
    '[发抖]': 'fadou.png',
    '[怄火]': 'ohuo.png',
    '[转圈]': 'zhuanquan.png',
    '[嘿哈]': 'heiha.png',
    '[捂脸]': 'wulian.png',
    '[奸笑]': 'jianxiao.png',
    '[机智]': 'jizhi.png',
    '[皱眉]': 'zhoumei.png',
    '[耶]': 'ye.png',
    '[蜡烛]': 'lazhu.png',
    '[红包]': 'hongbao.png',
    '[吃瓜]': 'chigua.png',
    '[加油]': 'jiayou.png',
    '[汗]': 'han.png',
    '[天啊]': 'tiana.png',
    '[Emm]': 'emm.png',
    '[社会社会]': 'shehuishehui.png',
    '[旺柴]': 'wangchai.png',
    '[好的]': 'haode.png',
    '[打脸]': 'dalian.png',
    '[加油加油]': 'jiayoujiayou.png',
    '[哇]': 'wa.png',
    '[發]': 'fa.png',
    '[福]': 'fu.png',
    '[鸡]': 'ji.png'
}








const InputBoxHeader: React.FC<
    {
        emoji: (emoji: string) => void,
        backFile: (file: any) => void,
        backImage: (file: any) => void,
        backVideo: (file: any) => void,
        conversation: any
    }> = ({ emoji, backFile, backImage, backVideo, conversation }) => {





        const fileInputRef = useRef<any>(null);
        const imageInputRef = useRef<any>(null);
        const videoInputRef = useRef<any>(null);

        const handleFileChange = (event: any) => {
            const file = event.target.files[0];
            backFile(file);
            event.target.value = null;
        };

        const handleImageChange = (event: any) => {
            const file = event.target.files[0];
            backImage(file);
            event.target.value = null;
        };

        const handleVideoChange = (event: any) => {
            const file = event.target.files[0];
            backVideo(file);
            event.target.value = null;
        };

        const IconFont = Icon.addFromIconFontCn({ src: '//at.alicdn.com/t/c/font_4634809_iex566rybui.js' });

        const dispatch = useDispatch();
        const call = (webrtc: any) => {
            dispatch(updateVideoUserId({ videoUserId: conversation.targetId, visible: true, call: "caller", webrtc }))

        }


        return <div className="h-[40px] bg-transparent w-full flex flex-row items-center px-[10px] justify-between">
            <div className="flex flex-row space-x-3">
                <Popover
                    content={
                        <div className="p-[12px] w-full bg-white grid grid-flow-row auto-rows-min grid-cols-7 gap-2 h-[250px] overflow-scroll ">

                            {
                                Object.entries(emojis).map(([key, value]) =>
                                    <img key={key} onClick={() => emoji(key)} src={`/emojis/${value}`} alt={key} className="w-7 cursor-pointer"></img>
                                )
                            }

                        </div>
                    }>
                    <IconFont type="icon-biaoqing_o" className="cursor-pointer  text-[25px] text-[#333]"></IconFont>
                </Popover>

                <input
                    ref={fileInputRef}
                    id="fileInput"
                    type="file"
                    style={{ display: 'none' }}
                    onChange={handleFileChange}
                />
                <input
                    ref={imageInputRef}
                    id="imageInput"
                    type="file"
                    accept="image/*"
                    style={{ display: 'none' }}
                    onChange={handleImageChange}
                />

                <input
                    ref={videoInputRef}
                    id="videoInput"
                    type="file"
                    accept="video/*"
                    style={{ display: 'none' }}
                    onChange={handleVideoChange}
                />

                <IconFont onClick={() => imageInputRef.current.click()} type="icon-tupian" className="text-[25px] cursor-pointer text-[#333]"></IconFont>
                <IconFont onClick={() => videoInputRef.current.click()} type="icon-shipin" className="text-[25px] cursor-pointer text-[#333]"></IconFont>
                <IconFont onClick={() => fileInputRef.current.click()} type="icon-wenjian1" className="text-[25px] cursor-pointer text-[#333]"></IconFont>
            </div >
            {

                conversation.type == ConversationType.private &&
                <div className="flex flex-row space-x-3">
                    <IconFont onClick={() => call('voice')} type="icon-yuyin" className="text-[25px] text-[#333]"></IconFont>
                    <IconFont onClick={() => call('video')} type="icon-shipin03-L" className="text-[25px] text-[#333]"></IconFont>
                </div>
            }
        </div >;
    }


export const InputBox: React.FC<{
    finshed: (text: string) => void,
    backFile: (file: any) => void,
    backVideo: (file: any) => void,
    backImage: (file: any) => void,
    conversation: any


}> = ({ finshed, backFile, backVideo, backImage, conversation }) => {

    const [text, setText] = useState('');
    const handleKeyDown = (event: any) => {
        if (event.ctrlKey && event.key === 'Enter') {
            event.preventDefault();
            setText(text + '\n');
        } else if (event.metaKey && event.key === 'Enter') {
            event.preventDefault();
            setText(text + '\n');
        } else if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            handleSend();
        }
    };

    const handleSend = () => {
        finshed(text)
        setText('');
    };

    const { showInput } = UseIsGroupUser(conversation);


    const [data, setData] = useState<any>([]);

    const handleSearch = (inputValue: any) => {
        setData(
            inputValue && inputValue.trim()
                ? new Array(5).fill(null).map((_, index) => `${inputValue}_${index}`)
                : []
        );
    };


    const users = [
        {
            id: 'walter',
            display: 'Walter White',
        },
        {
            id: 'pipilu',
            display: '皮皮鲁',
        },
        {
            id: 'luxixi',
            display: '鲁西西',
        },
        {
            id: 'satoshi1',
            display: '中本聪',
        },
        {
            id: 'satoshi2',
            display: 'サトシ・ナカモト',
        },
        {
            id: 'nobi',
            display: '野比のび太',
        },
        {
            id: 'sung',
            display: '성덕선',
        },
        {
            id: 'jesse',
            display: 'Jesse Pinkman',
        },
        {
            id: 'gus',
            display: 'Gustavo "Gus" Fring',
        },
        {
            id: 'saul',
            display: 'Saul Goodman',
        },
        {
            id: 'hank',
            display: 'Hank Schrader',
        },
        {
            id: 'skyler',
            display: 'Skyler White',
        },
        {
            id: 'mike',
            display: 'Mike Ehrmantraut',
        },
        {
            id: 'lydia',
            display: 'Lydìã Rôdarté-Qüayle',
        },
    ]


    return <div className="relative flex flex-col flex-grow border-t border-t-[#E6EBF5] w-full h-full">

        {

            showInput ? <div>
                <InputBoxHeader
                    conversation={conversation}
                    backFile={backFile}
                    backImage={backImage}
                    backVideo={backVideo}
                    emoji={(emoji) => {
                        setText(text + emoji);
                    }}
                />
                <div className="relative ">


                    <MentionsInput
                         value={text}
                         onChange={(e) => setText(e.target.value)}
                         onKeyDown={handleKeyDown}
                        style={defaultStyle}
                        className="h-[142px] text-[16px] text-gray-800 placeholder:text-[#7D8592] placeholder:text-[16px] w-full resize-none border-0  pl-[5px] pr-[7px] pb-5 text-left"
                        placeholder="在这里输入你的消息…"
                        a11ySuggestionsListLabel={"Suggested mentions"}
                    >
                        <Mention
                            markup="@[__display__](user:__id__)"
                            trigger="@"
                            data={[
                                { id: 'alice', display: '@alice' },
                                { id: 'bob', display: '@bob' },
                                { id: 'charlie', display: '@charlie' },
                            ]}
                            renderSuggestion={(
                                suggestion,
                                search,
                                highlightedDisplay,
                                index,
                                focused
                            ) => (
                                <div className={`user ${focused ? 'focused' : ''}`}>
                                    {highlightedDisplay}
                                </div>
                            )}
                        />
                    </MentionsInput>

                {/* <textarea
                        className="h-[142px] text-[16px] text-gray-800 placeholder:text-[#7D8592] placeholder:text-[16px] w-full resize-none border-0  pl-[12px] pr-[12px] pb-5"
                        placeholder="在这里输入你的消息…"
                        rows={5}
                        value={text}
                        onChange={(e) => setText(e.target.value)}
                        onKeyDown={handleKeyDown}
                    /> */}
                <div className="absolute right-6 bottom-3">
                    <div className="flex flex-row justify-center items-center">
                        <div className=" mr-[10px] text-[#999] text-[12px] p-[12px]">
                            <span> Ctrl+Enter：换行 </span>
                            <span> | </span>
                            <span>  Enter：发送 </span>
                        </div>
                        <div onClick={handleSend} className="w-[90px] h-7 rounded-lg bg-gradient-to-br from-sky-500 to-blue-500 shadow-md shadow-sky-300/50 text-white flex items-center justify-center cursor-pointer">发送</div>
                    </div>
                </div>

            </div>

            </div>
                :
<div className="flex flex-row justify-center items-center bg-gray-100 text-gray-500 h-[200px]">
    <IconInfoCircle className="text-[20px]" /><span className="ml-1 text-[16px]">无法在已退出的群聊中发送消息</span>
</div>
        }

    </div >;
}